package com.team1.system.blockchain.service;

import com.team1.common.utils.SecurityUtils;
import com.team1.system.blockchain.domain.Block;
import com.team1.system.blockchain.domain.BlockCache;
import com.team1.system.blockchain.domain.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.team1.system.blockchain.util.CryptoUtil.SHA256;

/**
 * 共识机制
 * 采用POW即工作量证明实现共识
 *
 */
@Service
public class PowService {

    @Autowired
    private BlockCache blockCache;

    @Autowired
    BlockService blockService;

    /**
     * 挖矿
     *
     * @return
     */
    public Block mine(List<Transaction> transactions){

        // 定义每次哈希函数的结果
        String newBlockHash = "";
        int nonce = 0;
        long start = System.currentTimeMillis();
        System.out.println("开始挖矿");
        while (true) {
            // 计算新区块hash值
            newBlockHash = SHA256(blockCache.getLatestBlock().getHash()+transactions+nonce);
            // 校验hash值
            if (isValidHash(newBlockHash)) {
                System.out.println("挖矿完成，正确的hash值：" + newBlockHash);
                System.out.println("挖矿耗费时间：" + (System.currentTimeMillis() - start) + "ms");
                break;
            }
            System.out.println("第"+(nonce+1)+"次尝试计算的hash值：" + newBlockHash);
            nonce++;
        }
        // 创建新的区块
        Block block = blockService.createNewBlock(nonce, blockCache.getLatestBlock().getHash(), newBlockHash, transactions);
        return block;
    }

    /**
     * 验证hash值是否满足系统条件
     * 暂定前2位是0则满足条件
     * @param hash
     * @return
     */
    public boolean isValidHash(String hash) {
        return hash.startsWith("00");
    }
}

